﻿using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;
using PetAdoptApi.Database;
using PetAdoptApi.Entity;
using PetAdoptApi.Extensions;
using PetAdoptionShared.Dto;
using System.Linq.Expressions;

namespace PetAdoptApi.Endpoints;

public class PetEndpoint
{
    public static void Map(RouteGroupBuilder rgb)
    {
        rgb.MapGet("newly/pageable", ([AsParameters]  PageableReqDto dto, AppDbContext db) => GetPetsPageableAsync(dto, db, query => query.OrderByDescending(p => p.Id)));
        rgb.MapGet("porpular/pageable", ([AsParameters] PageableReqDto dto, AppDbContext db) => GetPetsPageableAsync(dto, db, query => query.OrderByDescending(p => p.Views)));
        rgb.MapGet("random/pageable", ([AsParameters] PageableReqDto dto, AppDbContext db) => GetPetsPageableAsync(dto, db, query => query.OrderByDescending(_ => new Random().Next())));

        rgb.MapGet("detail/{id:int}", GetPetDetailAsync);
    }


    private static async Task<PetListDto[]> GetPetsPageableAsync(PageableReqDto dto, AppDbContext db, Func<IQueryable<Pet>, IOrderedQueryable<Pet>> orderExpression)
    {
        var pets = await orderExpression(db.Pets.Take(dto.pageSize).Skip(dto.pageSize * (dto.page - 1)))
            .Select(Selectors.PetToPetListDto)
            .ToArrayAsync();
        return pets;
    }

    private static async Task<PetDetailDto?> GetPetDetailAsync(int id, AppDbContext db)
    {
        var petDetail = await db.Pets.AsTracking().FirstOrDefaultAsync(p => p.Id == id);

        if (petDetail is not null)
        {
            petDetail.Views++;
            db.SaveChanges();
        }
        return petDetail?.MapToPetDetailDto();
    }
}
